package be.vdab.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

abstract class AbstractDAO {
	private static final String JNDI_NAME = "java:/comp/env/jdbc/CultuurHuis";

	public Connection getConnection() {
		Context context = null;
		try {
			context = new InitialContext();
			DataSource dataSource = (DataSource) context.lookup(JNDI_NAME);
			return dataSource.getConnection();
		} catch (NamingException ex) {
			throw new DAOException(JNDI_NAME + " niet gevonden", ex);
		} catch (SQLException ex) {
			throw new DAOException("kan geen connectie krijgen van "
					+ JNDI_NAME, ex);
		} finally {
			try {
				if (context != null) {
					context.close();
				}
			} catch (NamingException ex) {
				throw new DAOException("kan " + JNDI_NAME + " niet sluiten", ex);
			}
		}
	}

	public void close(Statement statement, Connection connection) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception ex) {
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {
        }
    }

    public void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (Exception ex) {
        }
        close(statement, connection);
    }

    public void close(Statement statement1, Statement statement2, Connection connection) {
        try {
            if (statement1 != null) {
                statement1.close();
            }
        } catch (Exception ex) {
        }
        close(statement2, connection);
    }
}

